<?php

namespace Modules\Book\Library;

use Modules\Book\Models\NodeBook;
use Phalcon\Events\Event;
use Core\Mvc\Entity\EntityInterface;
use Core\Forms\Form;
use Phalcon\Di;

class EntityListener
{
    protected $_oldBookId = false;

    public function links(Event $event, EntityInterface $entity, $links)
    {
        if ($entity->getEntity() == 'node' && $entity->getContentModel() == 'book') {
            $links['addBlock'] = array(
                'href' => array(
                    'for' => 'adminBookTocSort',
                    'book_id' => $entity->getId(),
                ),
                'icon' => 'danger',
                'name' => '管理书本',
            );
            $entity->setLinks($links);
        }
    }

    public function addForm(Event $event, EntityInterface $entity)
    {
        if ($entity->getEntity() == 'node' && $entity->getContentModel() != 'book') {
            $di = Di::getDefault();
            $field = $entity->getField();
            $field['book'] = $di->getShared('config')->get('book.entityNodeBook');
            $entity->setField($field);
        }
    }

    public function editForm(Event $event, EntityInterface $entity)
    {
        if ($entity->getEntity() == 'node' && $entity->getContentModel() != 'book') {
            $di = Di::getDefault();
            $field = $entity->getField();
            if (isset($entity->book_id)) {
                $this->_oldBookId = $entity->book_id;
            }
            $field['book'] = $di->getShared('config')->get('book.entityNodeBook');
            $entity->setField($field);
        }
    }

    public function saveBefore(Event $event, EntityInterface $entity)
    {
        $field = $entity->getField();
        if (!empty($field)) {
            $field = formFieldInit($field);
            foreach ($field as $key => $element) {
                if (isset($element['toc']) && isset($entity->{$key}) && is_string($entity->{$key}) && !empty($entity->{$key})) {
                    $output = Toc::toc($entity->{$key});
                    $entity->{$key} = $output['body'];
                    $entity->{$key . 'Toc'} = $output['toc'];
                }
            }
        }
    }

    public function saveAfter(Event $event, EntityInterface $entity)
    {
        if ($entity->getEntity() == 'node' && $entity->getContentModel() != 'book' && !is_null($entity->getForm())) {
            $form = $entity->getForm();
            $data = $form->getData();
            if (!isset($data['book_id']) || !$data['book_id']) {
                return false;
            }
            $nodeId = (string)$entity->getId();

            //没有变更所属书本
            if ($this->_oldBookId !== false && $data['book_id'] == $this->_oldBookId) {
                return true;
            }

            //变更所属书本，删除旧书本
            if ($this->_oldBookId !== false && $data['book_id'] != $this->_oldBookId) {
                $oldBook = NodeBook::findFirst([
                    'conditions' => [
                        'bid' => $this->_oldBookId
                    ]
                ]);
                //删除旧数据
                if ($oldBook) {
                    $toc = objectToArray($oldBook->toc);
                    $oldBook->toc = multInfoArrayDeleteItem($toc, $nodeId);
                    $oldBook->save();
                }

            }

            if ($data['book_id'] != 'null') {
                $nodeBook = NodeBook::findFirst([
                    'conditions' => [
                        'bid' => $data['book_id']
                    ]
                ]);
                if (!$nodeBook) {
                    $nodeBook = new NodeBook();
                }
                $toc = objectToArray($nodeBook->toc);
                $toc[$nodeId] = [
                    'title' => $entity->getTitle(),
                    'contentModel' => $entity->contentModel,
                ];
                $nodeBook->bid = $data['book_id'];
                $nodeBook->toc = $toc;
                $nodeBook->save();
            }
        }
    }
}